<?php
/**
 * quick_curd
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2025/08/10
 * 描述: api_xxx 代表前端接口,其它代表后端接口
 */

namespace app\result\auto;

use app\model\auto\Project;
use app\result\BaseResult;


class ProjectResult extends BaseResult
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new Project();
    }

    //列表页面配置
    public function list_config()
    {
        return $this->success_return('success', [
            'form_fields' => method_exists($this, 'form_fields') ? $this->form_fields() : [],
            'el_table_column' => $this->el_table_column(),
            'search_fields' => $this->_searchField()
        ]);
    }

    // 保存数据
    public function save_data($args): array
    {
        $formField = method_exists($this, 'form_fields') ? $this->form_fields() : [];
        if (!$formField) {
            return $this->error_return('请先定义表单字段');
        }
        $id = intval($args['id'] ?? 0);
        if ($id) {
            $data = $this->model->data_get(['id' => $id]);
            if (!$data) {
                return $this->error_return('数据不存在');
            }
        }
        $baseData = [];
        foreach ($formField as $field) {
            if ($id) {
                if ($field['isEditable']) {
                    if ($field['isRequired'] && !$args[$field['field']]) {
                        return $this->error_return('缺少必填项：' . $field['label']);
                    }
                    if (is_array($args[$field['field']])) {
                        $args[$field['field']] = implode(',', $args[$field['field']]);//默认用逗号分隔
                    }
                    $baseData[$field['field']] = $args[$field['field']] ?? $data[$field['field']];
                }
            } else {
                if ($field['isRequired'] && !$args[$field['field']]) {
                    return $this->error_return('缺少必填项：' . $field['label']);
                }
                if (is_array($args[$field['field']])) {
                    $args[$field['field']] = implode(',', $args[$field['field']]);//默认用逗号分隔
                }
                $baseData[$field['field']] = $args[$field['field']] ?? '';
            }
        }
        if ($id) {
            $this->model->data_update(['id' => $id], $baseData);
        } else {
            $this->model->data_add($baseData);
        }
        return $this->success_return('保存成功');
    }

    // 表单字段
    public function form_fields(): array
    {
        return [
            ['field' => 'project_name', 'label' => '项目名称', 'isEditable' => '1', 'isRequired' => '1', 'componentType' => 'input', 'optionsSource' => 'static',],
        ];
    }

    // 表格列
    public function el_table_column(): array
    {
        return [
            ['prop' => 'id', 'type' => 'text', 'label' => 'id', 'minWidth' => '120', 'align' => 'center',],
            ['prop' => 'project_name', 'type' => 'text', 'label' => '项目名称', 'minWidth' => '120', 'align' => 'center',],
            ['prop' => 'created_at', 'type' => 'text', 'label' => '创建时间', 'minWidth' => '120', 'align' => 'center',],
            ['prop' => 'updated_at', 'type' => 'text', 'label' => '更新时间', 'minWidth' => '120', 'align' => 'center',],
            ['prop' => '', 'type' => 'buttons', 'label' => '编辑', 'minWidth' => '130', 'align' => 'center', 'fixed' => 'right',
                'buttons' => [[
                    'label' => '编辑', 'action' => 'edit', 'icon' => 'el-icon-edit', 'type' => 'success', 'size' => 'mini',], [
                    'label' => '删除', 'action' => 'del', 'icon' => 'el-icon-delete', 'type' => 'danger', 'size' => 'mini',],]],
        ];
    }

    //列表搜索字段
    private function _searchField(): array
    {
        return [
            ['name' => 'project_name', 'label' => '项目名称', 'type' => 'input', 'placeholder' => '项目名称',],
        ];
    }

    // 获取公共条件限制
    private function _where($args = []): array
    {
        $where = [];

        if (!empty($args['project_name'])) {
            $where[] = ['project_name', '=', $args['project_name']];
        }
        return $where;
    }

    public function list($args = []): array
    {
        $page = intval($args['page'] ?? 1);
        $pageSize = intval($args['limit'] ?? 10);
        $sort_by = trim($args['sort_by'] ?? 'id desc');
        $where = $this->_where($args);
        $total = $this->model->data_count($where);
        $data = $this->model->data_list($where, '*', $sort_by, $page, $pageSize);
        return $this->success_return('success', [
            'total' => $total,
            'list' => $data,
        ]);
    }


    // 删除数据
    public function del_data($args): array
    {
        $ids = $args['ids'] ?? [];
        if (!$ids) {
            $ids = !empty($args['id']) ? [$args['id']] : [];
        }
        if (!$ids) {
            return $this->error_return('请选择数据');
        }
        $data = $this->model->data_list_nopage([["id", 'in', $ids]], '*');
        if (!$data) {
            return $this->error_return('数据不存在');
        }
        //判断是否存在del_time
        if (isset($data[0]['del_time'])) {
            $res = $this->model->data_update([["id", 'in', $ids]], ['del_time' => time()]);
        } else {
            $res = $this->model->data_del([["id", 'in', $ids]]);
        }
        if (!$res) {
            return $this->error_return('删除失败');
        }
        admin_log('删除客服数据', $data);
        return $this->success_return('删除成功');
    }

    // 获取下拉列表
    public function list_options($args = [], $options = false): array
    {
        $all = $this->model->data_list_nopage([], 'id,project_name');
        if ($all) {
            foreach ($all as &$item) {
                $item['label'] = $item['project_name'];
                $item['value'] = $item['id'];
            }
        }
        if ($options) {
            return $all;
        }
        return self::success_return('success', [
            'list' => $all,
        ]);
    }

}
